package com.urbainski.componentes.svc
{
	import com.urbainski.componentes.erro.ViewMsgErro;
	
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.remoting.Operation;
	import mx.rpc.remoting.RemoteObject;

	public class SvcFlexGenerico
	{
		
		protected var _svc : RemoteObject; 
		
		private var _result : Function;
		private var _fault : Function;
		
		public function SvcFlexGenerico(servico : String) {
			_svc = new RemoteObject();
			_svc.destination = servico;
		}
		
		public function executeMetodo(metodo : String, sucessFunction : Function, faultFunction : Function = null) : Operation {
			_result = sucessFunction;
			_fault = faultFunction;
			
			var operation : Operation = this._svc.getOperation(metodo) as Operation;
			operation.addEventListener(ResultEvent.RESULT, onResultSucess);
			operation.addEventListener(FaultEvent.FAULT, onResultFault);
			
			return operation;
		}
		
		private function onResultSucess(event : ResultEvent) : void {
			if(_result != null){
				_result(event);
			}
		}
		
		private function onResultFault(event : FaultEvent) : void {
			if(_fault != null){
				_fault.call(event);
				return;
			}
			
			//caso _fault seja null invoca janela de erro para mostrar a mensagem de 
			//erro para o usuario (desenvolver a janela)
			
			var viewErro : ViewMsgErro = new ViewMsgErro();
			viewErro.initView(event);
		}		
		
	}
}